package com.yzt.zhuju.network;

import com.yzt.zhuju.network.converter.MyConverterFactory;

import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * User: fish
 * E-mail: 709913163@qq.com
 * Date: 2022/11/29
 * Time: 17:31
 * describe:
 */
public class RetrofitClientManager {

    // 网络请求的baseUrl
    private String mBaseUrl;

    // 新增数据解析器
    private Converter.Factory mAddFactory;

    // 设置网络请求适配器
    private CallAdapter.Factory mCallFactory;

    // 设置OkHttpClient
    private OkHttpClient mOkHttpClient;

    private Retrofit retrofit;

    private static volatile RetrofitClientManager retrofitManager;

    public static RetrofitClientManager getInstance() {
        if (retrofitManager == null) {
            synchronized (RetrofitClientManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitClientManager();
                }
            }
        }
        return retrofitManager;
    }

    private RetrofitClientManager() {
    }

    // 设置BaseUrl
    public RetrofitClientManager setBaseUrl(String baseUrl) {
        this.mBaseUrl = baseUrl;
        return this;
    }

    // 设置数据解析
    public RetrofitClientManager addConverterFactory(Converter.Factory factory) {
        this.mAddFactory = factory;
        return this;
    }

    // 设置网络请求适配器
    public RetrofitClientManager addCallAdapterFactory(CallAdapter.Factory factory) {
        this.mCallFactory = factory;
        return this;
    }

    // 设置写入服务器的超时时间
    public RetrofitClientManager setOkHttpClient(OkHttpClient okHttpClient) {
        this.mOkHttpClient = okHttpClient;
        return this;
    }

    public <T> T getService(Class<T> tClass) {
        if (retrofit == null) {
            build();
        }
        return retrofit.create(tClass);
    }

    // 设置Build方法
    public Retrofit build() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(mBaseUrl);
        if (mAddFactory != null) {
            builder.addConverterFactory(mAddFactory);
        } else {
            builder.addConverterFactory(MyConverterFactory.create());
        }
        builder.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
        builder.client(mOkHttpClient);
        retrofit = builder.build();
        return retrofit;
    }
}
